﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using Liju.Common;
using Liju.Model;

namespace LiJu.Product
{
    public partial class ProductImgControl : UserControl
    {

        #region 变量定义
        bool MouseIsDown = false;
        Rectangle MouseRect = Rectangle.Empty; //矩形（为鼠标画出矩形选区）
        /// <summary>
        /// 所有螺丝列表
        /// </summary>
        public readonly List<ScrewControl> ScrewControls = null;
        /// <summary>
        /// 所有图片列表
        /// </summary>
        public readonly List<Image> ProductImgs = new List<Image>();
        /// <summary>
        /// 螺丝大小
        /// </summary>
        private int screwSize = 40;
        //运行拖拽任务标志
        public bool allowDragFlag = true;
        public bool AllowDragFlag
        {
            get { return allowDragFlag; }
            set
            {
                allowDragFlag = value;
                panel_main.Enabled = allowDragFlag;
            }
        }

        /// <summary>
        /// 当前删除任务产品序号
        /// </summary>
        private int currentDeleteWorkNum = 0;

        /// <summary>
        /// 当前删除任务号
        /// </summary>
        private int currentDeleteTaskNum = 0;

        /// <summary>
        /// 任务数
        /// </summary>
        public int TaskCount
        {
            get
            {
                return ScrewControls.Count;
            }
        }
        /// <summary>
        /// 产品图片数
        /// </summary>
        public int ImgCount
        {
            get
            {
                return panel_navigatebutton.Controls.Count;
            }
        }

        private ScrewControl screw;
        /// <summary>
        /// 螺丝控件
        /// </summary>
        public ScrewControl Screw
        {
            set
            {
                screw = value;
            }
            get
            {
                return screw;
            }
        }

        private bool addScrewFlag = false;
        /// <summary>
        /// 添加螺丝标志位
        /// </summary>
        public bool AddScrewFlag
        {
            get { return addScrewFlag; }
            set
            {
                addScrewFlag = value;
            }
        }

        /// <summary>
        /// 所属产品ID
        /// </summary>
        public long ProductId { get; set; }

        private Image productImg;
        /// <summary>
        /// 产品图片
        /// </summary>
        public Image ProductImg
        {
            set
            {
                productImg = value;
                this.picture_Product.Image = productImg;
                if (value != null && !ProductImgs.Exists(p => p.Tag == value?.Tag))
                {
                    ProductImgs.Add(productImg);
                    LoadNumButton();
                    panel_main.Controls.Clear();
                }

            }
            get
            {
                return productImg;
            }
        }

        private int currentImgNum = 0;
        /// <summary>
        /// 当前产品图片编号
        /// </summary>
        public int CurrentImgNum
        {
            get { return currentImgNum; }
            set
            {
                currentImgNum = value;
            }
        }


        /// <summary>
        /// 产品工序
        /// </summary>
        private int productWorkNum = 1;
        public int ProductWorkNum
        {
            get { return productWorkNum; }
            set
            {
                productWorkNum = value;
            }
        }

        /// <summary>
        /// 当前产品工序
        /// </summary>
        private int currentProductWorkNum = 1;
        public int CurrentProductWorkNum
        {
            get { return currentProductWorkNum; }
            set
            {
                currentProductWorkNum = value;
            }
        }

        /// <summary>
        /// 所有任务集合
        /// </summary>
        private List<TaskModel> allTaskModels = new List<TaskModel>();
        /// <summary>
        /// 所有产品图片集合
        /// </summary>
        private List<ProductImgModel> allProductImgModels = new List<ProductImgModel>();

        /// <summary>
        /// 任务拧紧图
        /// </summary>
        public PictureBox picWorking = null;
        private Timer timer;

        /// <summary>
        /// 添加任务事件
        /// </summary>
        public Action<TaskModel> AddTaskEvent;
        /// <summary>
        /// 选中任务事件
        /// </summary>
        public Action<int, int, bool> SelectTaskEvent;
        /// <summary>
        /// 删除任务事件
        /// </summary>
        public Action<List<int>, int> DeleteTaskEvent;
        /// <summary>
        /// 刷新任务
        /// </summary>
        public Action<List<WorkNumKeyValue>> RefreshTaskEvent;
        #endregion
        public ProductImgControl()
        {
            InitializeComponent();

            ScrewControls = new List<ScrewControl>();

            panel_main.MouseDown += new MouseEventHandler(Panel_MouseDown);
            panel_main.MouseUp += new MouseEventHandler(Panel_MouseUp);
            panel_main.MouseMove += new MouseEventHandler(Panel_MouseMove);

            picture_Product.SendToBack();
            this.panel_main.BackColor = Color.Transparent;
            this.panel_main.Parent = this.picture_Product;
            this.panel_main.BringToFront();

            picWorking = new PictureBox();
            picWorking.Image = Properties.Resources.ring;
            picWorking.Size = new Size(120, 120);
            picWorking.SizeMode = PictureBoxSizeMode.StretchImage;
            picWorking.Visible = false;
            picWorking.BackColor = Color.Transparent;
            this.panel_main.Controls.Add(picWorking);

            ProductEvent.SetTaskStatusEvent += SetTaskStatus;

            timer = new Timer();
            timer.Interval = 500;
            timer.Tick += new EventHandler(timer_Tick);
            timer.Start();

        }

        #region 方法

        #region 添加和拖拽螺丝
        /// <summary>
        /// 添加任务(螺丝)
        /// </summary>
        private void AddScrew(Point screwLocation)
        {
            ScrewControl screwControl = new ScrewControl();
            screwControl.ImgPath = ProductImg.Tag;
            screwControl.Location = screwLocation;
            screwControl.ImgNum = CurrentImgNum;
            screwControl.ControlPositon = screwLocation;
            screwControl.WorkNum = CurrentProductWorkNum;
            screwControl.Num = ScrewControls.Count + 1;
            screwControl.MouseDown += ScrewControl_MouseDown;
            screwControl.MouseUp += ScrewControl_MouseUp;
            screwControl.MouseMove += new MouseEventHandler(ScrewControl_MouseMove);
            screwControl.SelectEvent += ScrewControl_SelectEvent;
            screwControl.ContextMenuEvent += ContextMenuShow;
            ScrewControls.Add(screwControl);
            panel_main.Controls.Add(screwControl);

            TaskModel taskModel = new TaskModel()
            {
                WorkNum = screwControl.WorkNum,
                Num = screwControl.Num,
                ProductImgNum = CurrentImgNum,
                ScrewControlLocation = $"{screwLocation.X},{screwLocation.Y}",
                ScrewLocation = "0,0,0,0",
            };
            AddTaskEvent?.Invoke(taskModel);
        }


        /// <summary>
        /// 螺丝选择事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ScrewControl_SelectEvent(object sender, EventArgs e)
        {
            ScrewControl screwControl = sender as ScrewControl;
            if (screwControl != null)
            {
                SelectTaskEvent?.Invoke(screwControl.WorkNum, screwControl.Num - 1, screwControl.Selected);
            }

        }


        /// <summary>
        /// 显示右键菜单
        /// </summary>
        private void ContextMenuShow(Point point, int worknum, int num)
        {
            currentDeleteWorkNum = worknum;
            currentDeleteTaskNum = num;
            contextTaskMenu.Show(point);

        }
        /// <summary>
        /// 右键删除任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void deleteTasktoolStripMenuItem_Click(object sender, EventArgs e)
        {
            //if (currentDeleteTaskNum == 0)
            //{
            //    return;
            //}
            //int num = 0;
            //List<WorkNumKeyValue> deleteTaskList = new List<WorkNumKeyValue>();
            //deleteTaskList.Add(new WorkNumKeyValue() { WorkNum=currentDeleteWorkNum,Num=currentDeleteTaskNum});
            //ScrewControls.RemoveAll(c => c.WorkNum == currentDeleteWorkNum && c.Num==currentDeleteTaskNum);
            //for (int i = panel_main.Controls.Count - 1; i >= 0; i--)
            //{
            //    ScrewControl screw = (ScrewControl)panel_main.Controls[i];
            //    num++;
            //    if (screw.WorkNum == currentDeleteWorkNum && screw.Num == currentDeleteTaskNum)
            //    {
            //        panel_main.Controls.Remove(screw);
            //    }
            //}
            //List<WorkNumKeyValue> taskList = RefreshScrew();
            //if (deleteTaskList.Count > 0)
            //{
            //    DeleteTaskEvent?.Invoke(deleteTaskList, 0);
            //    RefreshTaskEvent?.Invoke(taskList);
            //}
            //currentDeleteWorkNum = 0;
            //currentDeleteTaskNum = 0;


            if (currentDeleteTaskNum == 0)
            {
                return;
            }
            int num = 0;
            List<int> deleteTaskList = new List<int>();
            deleteTaskList.Add(currentDeleteTaskNum);
            ScrewControls.RemoveAll(c => c.Num == currentDeleteTaskNum);
            for (int i = panel_main.Controls.Count - 1; i >= 0; i--)
            {
                ScrewControl screw = (ScrewControl)panel_main.Controls[i];
                num++;
                if (screw.Num == currentDeleteTaskNum)
                {
                    panel_main.Controls.Remove(screw);
                }
            }
            RefreshScrew();
            if (deleteTaskList.Count > 0)
            {
                DeleteTaskEvent?.Invoke(deleteTaskList, 0);
            }
            currentDeleteTaskNum = 0;

        }

        /// <summary>
        /// 添加任务(螺丝)
        /// </summary>
        public void AddExternalTask(ScrewControl screwControl)
        {
            screwControl.MouseDown += ScrewControl_MouseDown;
            screwControl.MouseUp += ScrewControl_MouseUp;
            screwControl.MouseMove += new MouseEventHandler(ScrewControl_MouseMove);
            screwControl.SelectEvent += ScrewControl_SelectEvent;
            screwControl.ContextMenuEvent += ContextMenuShow;
            ScrewControls.Add(screwControl);

        }
        private void ScrewControl_MouseUp(object sender, MouseEventArgs e)
        {
            dragFlag = false;
        }
        private void ScrewControl_MouseDown(object sender, MouseEventArgs e)
        {
            dragFlag = true;
        }

        private bool dragFlag = false;
        private void ScrewControl_MouseMove(object sender, MouseEventArgs e)
        {
            if (dragFlag && AllowDragFlag)
            {
                ScrewControl btn = (ScrewControl)sender;
                btn.Left += e.X - btn.Width / 2;
                btn.Top += e.Y - btn.Height / 2;

                btn.ControlPositon = btn.Location;
            }
        }
        #endregion

        #region 鼠标拖动多选螺丝
        private void ResizeToRectangle(object sender, Point p)
        {
            DrawRectangle(sender);
            MouseRect.Width = p.X - MouseRect.Left;
            MouseRect.Height = p.Y - MouseRect.Top;
            DrawRectangle(sender);
        }
        private void DrawRectangle(object sender)
        {
            Rectangle rect = ((Panel)sender).RectangleToScreen(MouseRect);
            ControlPaint.DrawReversibleFrame(rect, Color.White, FrameStyle.Dashed);
        }
        private void DrawStart(object sender, Point StartPoint)
        {
            ((Panel)sender).Capture = true;
            Cursor.Clip = ((Panel)sender).RectangleToScreen(((Panel)sender).Bounds);
            MouseRect = new Rectangle(StartPoint.X, StartPoint.Y, 0, 0);
        }
        private void DrawStop(object sender)
        {
            this.Capture = false;
            Cursor.Clip = Rectangle.Empty;
            MouseIsDown = false;
            DrawRectangle(sender);
            MouseRect = Rectangle.Empty;
        }
        private void Panel_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (!AddScrewFlag)
                {
                    MouseIsDown = true;
                    DrawStart(sender, e.Location);
                }
            }
            else if (e.Button == MouseButtons.Right)
            {
                DrawStop(sender);
            }

        }
        private void Panel_MouseUp(object sender, MouseEventArgs e)
        {
            if (AddScrewFlag && ProductImg != null)
            {
                Point screwLocation = new Point(e.X - screwSize / 2, e.Y - screwSize / 2);
                //添加螺丝
                AddScrew(screwLocation);
            }
            else
            {
                this.Capture = false;
                Cursor.Clip = Rectangle.Empty;
                MouseIsDown = false;
                DrawRectangle(sender);
                MouseRect = Rectangle.Empty;
            }
        }
        private void Panel_MouseMove(object sender, MouseEventArgs e)
        {
            if (MouseIsDown)
                ResizeToRectangle(sender, e.Location);

            foreach (var control in ((Panel)sender).Controls)
            {
                if (control is ScrewControl)
                {
                    ScrewControl screw = control as ScrewControl;
                    if (MouseRect.IntersectsWith(screw.Bounds)) //相交( MouseRect.Contains  完全包含)
                    {
                        screw.Selected = true;
                    }
                    else
                    {
                        int recLeft = MouseRect.X + MouseRect.Width;
                        int recTop = MouseRect.Y + MouseRect.Height;

                        if (screw.Bounds.X < MouseRect.X && screw.Bounds.X > recLeft && screw.Bounds.Y < MouseRect.Y && screw.Bounds.Y > recTop)
                        {
                            screw.Selected = true;
                        }
                    }
                }


            }

        }

        #endregion

        /// <summary>
        /// 导入螺丝
        /// </summary>
        public void LoadScrewButtons()
        {
            panel_main.Controls.Clear();
            List<ScrewControl> screws = ScrewControls.FindAll(o => o.ImgNum == CurrentImgNum);
            foreach (var screwControl in screws)
            {
                screwControl.Location = screwControl.ControlPositon;
                panel_main.Controls.Add(screwControl);
            }

        }

        /// <summary>
        /// 删除选中螺丝
        /// </summary>
        public void DeleteSelectScrew()
        {
            int num = 0;
            List<int> deleteTaskList = new List<int>();

            deleteTaskList = ScrewControls.Where(o => o.Selected == true).Select(c => c.Num).ToList();
            ScrewControls.RemoveAll(c => c.Selected == true);
            for (int i = panel_main.Controls.Count - 1; i >= 0; i--)
            {
                ScrewControl screw = (ScrewControl)panel_main.Controls[i];
                num++;
                if (screw.Selected)
                {
                    panel_main.Controls.Remove(screw);
                }
            }
            RefreshScrew();
            if (deleteTaskList.Count > 0)
            {
                DeleteTaskEvent?.Invoke(deleteTaskList, 0);
            }

            //int num = 0;
            //List<WorkNumKeyValue> deleteTaskList = new List<WorkNumKeyValue>();
            //foreach(var task in ScrewControls)
            //{
            //    if(task.Selected)
            //    {
            //        deleteTaskList.Add(new WorkNumKeyValue { WorkNum=task.WorkNum,Num=task.Num });
            //    }
            //}
            //ScrewControls.RemoveAll(c => c.Selected == true);
            //for (int i = panel_main.Controls.Count - 1; i >= 0; i--)
            //{
            //    ScrewControl screw = (ScrewControl)panel_main.Controls[i];
            //    num++;
            //    if (screw.Selected)
            //    {
            //        panel_main.Controls.Remove(screw);
            //    }
            //}
            //List<WorkNumKeyValue> taskList =RefreshScrew();
            //if (deleteTaskList.Count > 0)
            //{
            //    DeleteTaskEvent?.Invoke(deleteTaskList, 0);
            //    RefreshTaskEvent?.Invoke(taskList);
            //}

        }

        /// <summary>
        /// 删除所有螺丝
        /// </summary>
        public void DeleteAllScrew()
        {
            for (int i = panel_main.Controls.Count - 1; i >= 0; i--)
            {
                ScrewControl screw = (ScrewControl)panel_main.Controls[i];
                panel_main.Controls.Remove(screw);
                ScrewControls.Remove(screw);
            }
            ScrewControls.Clear();
        }

        /// <summary>
        /// 删除产品图时，刷新螺丝控件
        /// </summary>
        public void RefreshScrew(int imgNum)
        {
            int num = 0;
            foreach (var screwControl in ScrewControls)
            {
                num++;
                screwControl.Num = num;
                screwControl.Selected = false;
                if (screwControl.ImgNum >= imgNum)
                {
                    screwControl.ImgNum = screwControl.ImgNum - 1;
                }
            }
        }

        /// <summary>
        /// 刷新螺丝控件
        /// </summary>
        public void RefreshScrew()
        {
            int num = 0;
            foreach (var screwControl in ScrewControls)
            {
                num++;
                screwControl.Num = num;
            }
        }

        /// <summary>
        /// 选择螺丝
        /// </summary>
        public void SelectScrews(List<WorkNumKeyValue> tasks)
        {
            foreach (ScrewControl screwControl in ScrewControls)
            {
                screwControl.Selected = false;
            }
            if (tasks.Count > 0)
            {
                int firstnum = 0;
                int firstImgNum = 1;
                foreach (var num in tasks)
                {
                    ScrewControl screwControl = ScrewControls.Find(c => c.WorkNum == num.WorkNum && c.Num == num.Num);
                    if (screwControl != null)
                    {
                        if (firstnum == 0)
                        {
                            firstImgNum = screwControl.ImgNum;
                        }
                        screwControl.Selected = true;
                    }
                    firstnum++;
                }
                ChangeProductImgIndex(firstImgNum);
            }

        }

        /// <summary>
        /// 更新电批位置
        /// </summary>
        /// <param name="num"></param>
        /// <param name="location"></param>
        public void UpdateScrewLocation(int num, string location)
        {
            ScrewControl screwControl = ScrewControls.Find(c => c.Num == num);
            if (screwControl != null)
            {
                screwControl.ScrewLocation = location;
                screwControl.Selected = true;
            }
        }

        /// <summary>
        /// 清除所有选中任务
        /// </summary>
        public void ClearAllSelectScrews()
        {
            foreach (ScrewControl screwControl in ScrewControls)
            {
                screwControl.Selected = false;
            }
        }

        /// <summary>
        /// 导入导航按钮
        /// </summary>
        public void LoadNumButton()
        {
            this.panel_navigatebutton.Controls.Clear();
            NavigateButton lastNavigateButton = null;
            for (int i = 0; i < ProductImgs.Count; i++)
            {
                NavigateButton navigateButton = new NavigateButton() { Num = i + 1 };
                navigateButton.Left = navigateButton.Width * i;
                navigateButton.Cursor = Cursors.Hand;
                navigateButton.SelectEvent += NavigateButton_SelectEvent;
                if (i == ProductImgs.Count - 1)
                {
                    lastNavigateButton = navigateButton;
                    lastNavigateButton.Selected = true;
                    CurrentImgNum = navigateButton.Num;
                }
                panel_navigatebutton.Controls.Add(navigateButton);
            }
            panel_navigatebutton.Width = screwSize * ProductImgs.Count + 5;
            panel_navigatebutton.Left = this.Width / 2 - panel_navigatebutton.Width / 2;
        }

        /// <summary>
        /// 导航按钮选中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void NavigateButton_SelectEvent(object sender, EventArgs e)
        {
            NavigateButton selectNavigateButton = sender as NavigateButton;
            if (selectNavigateButton != null)
            {
                ProductImg = ProductImgs[selectNavigateButton.Num - 1];
                CurrentImgNum = selectNavigateButton.Num;
            }

            foreach (var control in panel_navigatebutton.Controls)
            {
                if (control is NavigateButton)
                {
                    NavigateButton navigateButton = control as NavigateButton;
                    if (navigateButton.Num != selectNavigateButton.Num)
                    {
                        navigateButton.Selected = false;
                    }

                }
            }
            LoadScrewButtons();
        }

        /// <summary>
        /// 删除选中产品图片
        /// </summary>
        public void DeleteSelectProductImg()
        {
            List<int> deleteTaskList = new List<int>();
            int deleteImgNum = CurrentImgNum;
            for (int i = panel_navigatebutton.Controls.Count - 1; i >= 0; i--)
            {
                NavigateButton navigateButton = panel_navigatebutton.Controls[i] as NavigateButton;
                if (navigateButton.Selected)
                {
                    panel_navigatebutton.Controls.Remove(navigateButton);
                    //string picFolder = Directory.GetCurrentDirectory() + $"\\Picture\\";
                    //string picName = picture_Product.Image.Tag.ToString();
                    //string sourcPicturePath = Path.Combine(picFolder, picName);
                    //try
                    //{
                    //    if (File.Exists(sourcPicturePath))
                    //    {
                    //        File.Delete(sourcPicturePath);
                    //    }
                    //}
                    //catch (Exception ex)
                    //{
                    //    Console.WriteLine($"删除产品图错误->{ex.Message}");
                    //}
                    ProductImgs.Remove(ProductImgs[navigateButton.Num - 1]);
                    deleteTaskList = ScrewControls.Where(o => o.ImgNum == navigateButton.Num).Select(c => c.Num).ToList();
                    if (panel_navigatebutton.Controls.Count > 0)
                    {
                        LoadNumButton();
                        NavigateButton lastNavigateButton = panel_navigatebutton.Controls[panel_navigatebutton.Controls.Count - 1] as NavigateButton;
                        ScrewControls.RemoveAll(c => c.ImgNum == navigateButton.Num);
                        RefreshScrew(deleteImgNum);
                        lastNavigateButton.SelectChanged();

                    }
                    else
                    {
                        ProductImgs.Clear();
                        panel_main.Controls.Clear();
                        ScrewControls.Clear();
                        panel_navigatebutton.Controls.Clear();
                        ProductImg = null;
                    }

                    break;
                }
            }

            if (deleteTaskList.Count > 0)
            {
                DeleteTaskEvent?.Invoke(deleteTaskList, deleteImgNum);
            }
        }

        /// <summary>
        /// 删除所有产品图片
        /// </summary>
        public void DeleteAllProductImg()
        {
            //foreach(Image img in ProductImgs)
            //{
            //    string picFolder = Directory.GetCurrentDirectory() + $"\\Picture\\";
            //    string picName = picture_Product.Image.Tag.ToString();
            //    string sourcPicturePath = Path.Combine(picFolder, picName);
            //    try
            //    {
            //        if (File.Exists(sourcPicturePath))
            //        {
            //            File.Delete(sourcPicturePath);
            //        }
            //    }
            //    catch (Exception ex)
            //    {
            //        Console.WriteLine($"删除产品图错误->{ex.Message}");
            //    }
            //}
            ProductImgs.Clear();
            panel_main.Controls.Clear();
            ScrewControls.Clear();
            panel_navigatebutton.Controls.Clear();
            ProductImg = null;
        }

        /// <summary>
        /// 切换产品图片
        /// </summary>
        /// <param name="num"></param>
        public void ChangeProductImgIndex(int num)
        {
            if (ProductImgs.Count >= num)
            {
                var tempImg = ProductImgs[num - 1];
                if (tempImg.Tag != ProductImg.Tag)
                {
                    ProductImg = ProductImgs[num - 1];
                }
                CurrentImgNum = num;
                foreach (var control in panel_navigatebutton.Controls)
                {
                    if (control is NavigateButton)
                    {
                        NavigateButton navigateButton = control as NavigateButton;
                        if (navigateButton.Num != num)
                        {
                            navigateButton.Selected = false;
                        }
                        else
                        {
                            navigateButton.Selected = true;
                        }

                    }
                }
                LoadScrewButtons();
            }

        }

        /// <summary>
        /// 旋转图片
        /// </summary>
        public void RotateProductImg()
        {
            if (picture_Product.Image == null || picture_Product.Image.Tag == null)
            {
                return;
            }
            string picFolder = Directory.GetCurrentDirectory() + $"\\Picture\\";
            string picName = picture_Product.Image.Tag.ToString();
            string sourcPicturePath = Path.Combine(picFolder, picName);
            Image sourcPicture = ProductImgs.Find(p => p.Tag == picture_Product.Image.Tag);
            List<ScrewControl> screwControls = ScrewControls.FindAll(c => c.ImgPath == picture_Product.Image.Tag);
            // 将图片旋转90度
            picture_Product.Image.RotateFlip(RotateFlipType.Rotate90FlipNone);
            picture_Product.Refresh();
            Image imageRotate = picture_Product.Image;
            string rotatepicName = DateTime.Now.ToString("yyyyMMddHHmmss") + System.IO.Path.GetExtension(sourcPicturePath);
            string rotatepicPath = Path.Combine(Path.GetDirectoryName(sourcPicturePath), rotatepicName);
            picture_Product.Image.Tag = rotatepicName;
            picture_Product.Image.Save(rotatepicPath);
            imageRotate.Tag = rotatepicName;
            sourcPicture = imageRotate;
            foreach (var control in screwControls)
            {
                control.ImgPath = imageRotate.Tag;
            }
            productImg = imageRotate;
            //if (File.Exists(sourcPicturePath))
            //{
            //    File.Delete(sourcPicturePath);
            //}
        }

        /// <summary>
        /// 清理数据
        /// </summary>
        public void ClearData(bool addTaskFlag = false)
        {
            ScrewControls.Clear();
            ProductImgs.Clear();
            panel_main.Controls.Clear();
            panel_navigatebutton.Controls.Clear();
            CurrentImgNum = 0;
            ProductImg = null;
            if (addTaskFlag == false)
            {
                addScrewFlag = false;
            }
        }

        /// <summary>
        /// 清除测试数据
        /// </summary>
        public void CleartTestData()
        {
            foreach (ScrewControl screw in ScrewControls)
            {
                screw.pic1.Visible = false;
                picWorking.Visible = false;
                screw.Selected = false;
                screw.Status = TestStatus.Unknow;
            }
        }


        bool picWorkFlag = false;
        /// <summary>
        /// 执行中螺丝定时闪烁
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer_Tick(object sender, EventArgs e)
        {
            if (picWorking.Visible)
            {
                picWorkFlag = !picWorkFlag;
                if (picWorkFlag)
                {
                    picWorking.Size = new Size(80, 80);
                    picWorking.Location = new Point(picWorking.Location.X + 20, picWorking.Location.Y + 20);
                }
                else
                {
                    picWorking.Size = new Size(120, 120);
                    picWorking.Location = new Point(picWorking.Location.X - 20, picWorking.Location.Y - 20);
                }
                picWorking.Refresh();
            }
        }

        /// <summary>
        /// 设置任务状态 半圆0,全圆1
        /// </summary>
        /// <param name="worknum"></param>
        /// <param name="num"></param>
        /// <param name="testStatus"></param>
        /// <param name="circleState">对预拧螺丝进行半圆0,全圆1 显示控制</param>
        public void SetTaskStatus(int worknum, int num, TestStatus testStatus,int circleState= 1)
        {


            this.BeginInvoke(new Action(() =>
            {
                if (CurrentProductWorkNum != worknum)
                {
                    CurrentProductWorkNum = worknum;
                    //ChangeWorkNum(worknum); //20241111zhl 注释原因:1.非工序1首次作业不显示图片；2.重复调用InitProductImg
                }
                ScrewControl screwControl = ScrewControls.Find(c => c.Num == num);
                if (screwControl != null)
                {
                    foreach (ScrewControl screw in ScrewControls)
                    {
                        screw.pic1.Visible = false;
                        picWorking.Visible = false;
                        if (screw.Status != TestStatus.Pass && screw.Status != TestStatus.NG)
                        {
                            screw.Selected = false;
                        }
                    }
                    screwControl.Status = testStatus;
                    screwControl.CircleState = circleState;
                    ChangeProductImgIndex(screwControl.ImgNum);
                    if (testStatus == TestStatus.ReadyStart)
                    {
                        screwControl.BackGroundColor = ScrewColor.ReadyStartColor;
                        PicWorkingSet(screwControl, Properties.Resources.ring2);
                    }
                    else if (testStatus == TestStatus.ReadyTest)
                    {
                        screwControl.BackGroundColor = ScrewColor.ReadyTestColor;
                        PicWorkingSet(screwControl, Properties.Resources.ring2);
                    }
                    else if (testStatus == TestStatus.Testing)
                    {
                        screwControl.picNum.Text = num.ToString();
                        screwControl.Selected = false;
                        screwControl.pic1.Visible = true;
                        PicWorkingSet(screwControl,Properties.Resources.ring);
                    }
                    else if (testStatus == TestStatus.Pass)
                    {
                        screwControl.BackGroundColor = ScrewColor.TestPassColor;
                    }
                    else if (testStatus == TestStatus.NG)
                    {
                        screwControl.BackGroundColor = ScrewColor.TestNGColor;
                    }
                }

            }));
        }
        /// <summary>
        /// 闪烁控制
        /// </summary>
        /// <param name="screwControl"></param>
        /// <param name="img"></param>
        private void PicWorkingSet(ScrewControl screwControl, Bitmap img)
        {
            picWorking.Location = new Point(screwControl.ControlPositon.X - (picWorking.Width - screwControl.Width) / 2, screwControl.Location.Y - (picWorking.Height - screwControl.Height) / 2);
            picWorking.BringToFront();
            picWorking.Visible = true;
            picWorking.Parent = this.panel_main;
            picWorking.Image = img;
        }

        /// <summary>
        /// 初始化产品图片控件
        /// </summary>
        public void InitProductImg(List<ProductImgModel> productImgs, List<TaskModel> tasks, bool addTaskFlag = false)
        {
            ClearData(addTaskFlag);
            if (productImgs != null && productImgs.Count > 0)
            {
                ProductId = productImgs[0].ProductId;
                foreach (ProductImgModel productImgModel in productImgs)
                {
                    string picFolder = Directory.GetCurrentDirectory() + $"\\Picture\\";
                    string picName = productImgModel.Path;
                    string productImgPath = Path.Combine(picFolder, picName);
                    if (File.Exists(productImgPath))
                    {
                        Image img = Image.FromFile(productImgPath);
                        img.Tag = productImgModel.Path;
                        ProductImg = img;
                    }
                    else
                    {
                        Console.WriteLine($"RefreshProducDetials->图片不存在:{productImgPath}");
                        return;
                    }

                }
                List<ScrewControl> screws = new List<ScrewControl>();
                foreach (TaskModel task in tasks)
                {
                    ScrewControl screw = new ScrewControl
                    {
                        WorkNum = task.WorkNum,
                        Num = task.Num,
                        ImgNum = task.ProductImgNum,
                        TightenPrepare = task.TightenPrepare
                    };
                    string picName = productImgs.Find(t => t.ImgIndex == task.ProductImgNum).Path;
                    string picFolder = Directory.GetCurrentDirectory() + $"\\Picture\\";
                    string productImgPath = Path.Combine(picFolder, picName);

                    if (!File.Exists(productImgPath))
                    {
                        Console.WriteLine($"RefreshProducDetials->图片不存在:{productImgPath}");
                        return;
                    }
                    screw.ImgPath = productImgPath;
                    screw.ScrewLocation = screw.ScrewLocation;
                    string[] screwLocation = task.ScrewControlLocation.Split(',');
                    if (screwLocation.Length == 2)
                    {
                        int.TryParse(screwLocation[0], out int x);
                        int.TryParse(screwLocation[1], out int y);
                        Point screwPoint = new Point(x, y);
                        screw.ControlPositon = screwPoint;
                        screw.Location = screwPoint;
                    }
                    AddExternalTask(screw);
                }
                LoadScrewButtons();
            }
        }


        /// <summary>
        /// 初始化产品数据
        /// </summary>
        public void InitProductData(List<ProductImgModel> productImgs, List<TaskModel> tasks)
        {
            ClearData(false);
            if (productImgs != null && productImgs.Count > 0)
            {
                allProductImgModels.Clear();
                allTaskModels.Clear();
                allProductImgModels.AddRange(productImgs);
                allTaskModels.AddRange(tasks);
            }
        }

        /// <summary>
        /// 切换产品工序
        /// </summary>
        public void ChangeWorkNum(int worknum)
        {
            CurrentProductWorkNum = worknum;
            List<ProductImgModel> productImgModels = allProductImgModels.FindAll(p => p.WorkNum == CurrentProductWorkNum);
            List<TaskModel> taskModels = allTaskModels.FindAll(p => p.WorkNum == CurrentProductWorkNum);
            InitProductImg(productImgModels, taskModels, false);
        }

        #endregion

    }

    public class WorkNumKeyValue
    {
        public int WorkNum { get; set; }
        public int Num { get; set; }
    }
}
